<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import gsap from 'gsap'
import { getCode } from '@/api/loginApi'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const userStore = useUserStore()

// Form data
const loginForm = reactive({
  username: '',
  password: '',
  code: '',
  uuid: '',
})

// 验证码图片
const captchaImg = ref('')
const captchaEnabled = ref(false)

// 获取验证码
const getCaptcha = async () => {
  try {
    const res = await getCode()
    // 直接处理响应数据，不假设有额外的嵌套
    if (res.success) {
      captchaImg.value = 'data:image/gif;base64,' + res.data.img
      loginForm.uuid = res.data.uuid
      captchaEnabled.value = res.data.captchaEnabled
    } else {
      console.error('获取验证码失败:', res.msg)
      ElMessage.error(res.msg || '获取验证码失败')
    }
  } catch (error) {
    console.error('获取验证码失败:', error)
    ElMessage.error('获取验证码失败，请刷新页面重试')
  }
}

// Form rules
const rules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' },
  ],
  code: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
})

// Form ref
const loginFormRef = ref(null)
const formContainer = ref(null)
const featureContainer = ref(null)
const layoutContainer = ref(null)
// Loading state
const loading = ref(false)

// Handle login submission
const handleLogin = async () => {
  console.log('handleLogin')
  if (!loginFormRef.value) return

  loginFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        // 使用 user store 调用登录接口
        const res = await userStore.fetchUserLogin({
          username: loginForm.username,
          password: loginForm.password,
          code: loginForm.code,
          uuid: loginForm.uuid,
        })

        // 直接处理响应数据
        if (res.success) {
          ElMessage.success(res.msg || '登录成功')
          // 登录成功动画
          // 表单容器动画 - 向右退出
          gsap.to(formContainer.value, {
            opacity: 0,
            x: 30,
            duration: 0.6,
            ease: 'power3.in',
          })

          // 左侧内容动画 - 向左退出
          gsap.to(featureContainer.value, {
            opacity: 0,
            x: -90,
            duration: 0.6,
            ease: 'power3.in',
          })

          // 表单元素逐个消失
          gsap.to('.fade-in-item', {
            opacity: 0,
            y: -10,
            x: 30,
            stagger: 0.1,
            duration: 0.4,
          })

          // 最后整体消失并跳转
          gsap.to(layoutContainer.value, {
            opacity: 0,
            scale: 0.95,
            delay: 0.6,
            duration: 0.1,
            onComplete: () => router.push({ name: 'home' }),
          })
        } else {
          ElMessage.error(res.msg || '登录失败')
          // 重新获取验证码
          getCaptcha()
        }
      } catch (error) {
        ElMessage.error('登录失败，请稍后重试')
        console.error('登录失败:', error)
        // 重新获取验证码
        loginForm.code = ''
        getCaptcha()
      } finally {
        loading.value = false
      }
    } else {
      return false
    }
  })
}

// 初始化动画
onMounted(() => {
  // 获取验证码
  getCaptcha()

  // 表单容器动画
  gsap.from(formContainer.value, {
    opacity: 0,
    x: -30,
    duration: 0.8,
    ease: 'power3.out',
  })

  // 左侧内容动画
  gsap.from(featureContainer.value, {
    opacity: 0,
    x: -30,
    duration: 0.8,
    ease: 'power3.out',
  })

  // 表单元素逐个显示
  gsap.from('.fade-in-item', {
    opacity: 0,
    y: 20,
    x: -30,
    stagger: 0.1,
    duration: 0.6,
    delay: 0.1,
  })
})
</script>

<template>
  <div class="flex h-screen w-full overflow-hidden" ref="layoutContainer">
    <!-- 左侧 - 特性展示 -->
    <div ref="featureContainer" class="login-bg w-[60%] flex items-center justify-center">
      <div class="text-white text-center px-10 w-full">
        <h2 class="text-4xl font-medium mb-6 fade-in-item">欢迎使用智慧助农管理系统</h2>
        <h3 class="text-2xl opacity-90 font-light fade-in-item">
          专注于助农，提升农产品销售与发展
        </h3>

        <!-- 添加简单的图标特性列表 -->
        <div class="mt-10 grid grid-cols-3 gap-6 text-left max-w-xl mx-auto fade-in-item">
          <div class="flex items-start space-x-3">
            <div class="bg-white bg-opacity-20 p-2 rounded-lg">
              <LineMdMushroomTwotone class="text-black" />
            </div>
            <div>
              <h4 class="font-medium">农产品管理</h4>
              <p class="text-sm opacity-80">高效管理产品信息和销售数据</p>
            </div>
          </div>
          <div class="flex items-start space-x-3">
            <div class="bg-white bg-opacity-20 p-2 rounded-lg">
              <LineMdPhoneCallTwotoneLoop class="text-black" />
            </div>
            <div>
              <h4 class="font-medium">销售支持</h4>
              <p class="text-sm opacity-80">提供销售工具，助力农产品推广</p>
            </div>
          </div>
          <div class="flex items-start space-x-3">
            <div class="bg-white bg-opacity-20 p-2 rounded-lg">
              <LineMdSecurityTwotone class="text-black" />
            </div>
            <div>
              <h4 class="font-medium">安全保障</h4>
              <p class="text-sm opacity-80">确保数据安全，保护用户隐私</p>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div ref="formContainer" class="w-[40%] flex items-center justify-center bg-white shadow-lg">
      <div class="w-4/5 max-w-md py-8">
        <h1 class="text-3xl font-bold text-gray-800 mb-8 fade-in-item">智慧商品管理系统</h1>
        <el-form
          ref="loginFormRef"
          :model="loginForm"
          :rules="rules"
          class="w-full space-y-4"
          label-position="top"
        >
          <el-form-item label="用户名" prop="username" class="fade-in-item">
            <el-input
              v-model="loginForm.username"
              placeholder="请输入用户名"
              class="h-11 rounded-md hover:shadow-sm transition-all"
            />
          </el-form-item>

          <el-form-item label="密码" prop="password" class="fade-in-item">
            <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码"
              show-password
              class="h-11 rounded-md hover:shadow-sm transition-all"
            />
          </el-form-item>

          <!-- 验证码输入区域 -->
          <el-form-item label="验证码" prop="code" class="fade-in-item">
            <div class="flex w-full items-center space-x-3">
              <el-input
                v-model="loginForm.code"
                placeholder="请输入验证码"
                class="h-11 rounded-md hover:shadow-sm transition-all"
                @keyup.enter="handleLogin"
              />
              <div class="captcha-img cursor-pointer h-11 flex-shrink-0" @click="getCaptcha">
                <img
                  :src="captchaImg"
                  alt="验证码"
                  class="h-full rounded-md border border-gray-200"
                  v-if="captchaImg"
                />
                <div
                  v-else
                  class="h-full flex items-center justify-center bg-gray-100 rounded-md border border-gray-200 px-2"
                >
                  加载中...
                </div>
              </div>
            </div>
          </el-form-item>

          <el-form-item class="fade-in-item">
            <el-button
              type="primary"
              @click="handleLogin"
              :loading="loading"
              class="w-full h-11 text-base font-medium mt-4 rounded-md shadow-sm hover:shadow-md transition-all login-btn"
            >
              <LineMdLogIn v-if="!loading" />
              登录
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<style scoped>
.login-bg {
  position: relative;
  background: url('@/assets/images/login-bg.jpg') no-repeat center center;
  background-size: cover;
  border-radius: 0px 10px 10px 0px;
}

.login-bg::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.3);
  z-index: 1;
  border-radius: 0px 10px 10px 0px;
  transition: background 0.5s ease-in-out;
}

.login-bg:hover::before {
  background: rgba(0, 0, 0, 0.1);
}

/* 确保内容在遮罩层之上 */
.login-bg > div {
  position: relative;
  z-index: 2;
}

/* 可能仍需要的自定义样式 */
:deep(.el-input__wrapper),
:deep(.el-button) {
  border-radius: 0.375rem;
}

/* 修复一些边缘样式问题 */
:deep(.el-checkbox__label) {
  font-size: 14px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  padding-bottom: 4px;
}

.captcha-img {
  width: 120px;
  overflow: hidden;
}
</style>
